/*
 * @Descripttion:
 * @version:
 * @Author: pyq
 * @Date: 2024-10-15 23:59:41
 * @LastEditors: pyq
 * @LastEditTime: 2024-10-18 22:12:14
 */
import { errorResponse } from "../utils/responseHelper.js";
import getRedisClient from "../utils/redisClient.js";

const authMiddleware = async(ctx, next) => {
    return await next();

    console.log(ctx.path);

    if (ctx.path.startsWith("/api")) {
        return await next();
    }
    const token = ctx.request.headers["authorization"];

    if (!token) {
        errorResponse(ctx, 401, "No token");
        return;
    }

    try {
        const redis = await getRedisClient();
        const userData = await redis.get(`user:${token}`);

        if (!userData) {
            errorResponse(ctx, 401, "登录过期");
            return;
        }

        try {
            const redis = await getRedisClient();
            const userData = await redis.get(`user:${token}`);

            if (!userData) {
                errorResponse(ctx, 401, "登录过期");
                return;
            }
            await redis.expire(`user:${token}`, 3600); // 设置1小时的过期时间
            ctx.state.user = JSON.parse(userData);
            await next();
        } catch (error) {
            console.error("Error fetching user data from Redis:", error);
            errorResponse(ctx, 500, "error");
            throw error;
        }
    } catch (error) {
        console.error("Error fetching user data from Redis:", error);
        errorResponse(ctx, 500, "error");
        throw error;
    }
};

export default authMiddleware;